package com.example.util;

public class ByteUtil {

    public static int byteArrayToPort(byte[] bytes) {
        if (bytes == null || bytes.length != 2) {
            throw new IllegalArgumentException("Byte array must be of length 2 to represent a port number.");
        }
        // 使用位操作合并两个byte，注意可能需要考虑大小端
        int port = (bytes[0] & 0xFF) << 8 | (bytes[1] & 0xFF);
        return port;
    }

    public static String byteToMacAddressString(byte[] macAddress) {
        // 确保byte数组长度为6
        if (macAddress != null && macAddress.length == 6) {
            // 使用String.format()将byte数组格式化为MAC地址的字符串格式
            return String.format(
                    "%02X:%02X:%02X:%02X:%02X:%02X",
                    macAddress[0], macAddress[1], macAddress[2],
                    macAddress[3], macAddress[4], macAddress[5]
            );
        }
        return null; // 如果byte数组不是6个字节，则返回null或抛出异常
    }

    public static String bytesToIP(byte[] bytes) {
        // 确保bytes数组长度为4
        if (bytes == null || bytes.length != 4) {
            throw new IllegalArgumentException("byte array must be length 4");
        }

        // 转换为整数
        int firstByte = bytes[0] & 0xFF;
        int secondByte = bytes[1] & 0xFF;
        int thirdByte = bytes[2] & 0xFF;
        int fourthByte = bytes[3] & 0xFF;

        // 转换为IP地址字符串
        return String.format("%d.%d.%d.%d", firstByte, secondByte, thirdByte, fourthByte);
    }

}
